import 'dart:ui';

import 'package:flame/components.dart';
import 'package:flutter_fireworks/fire/firework_effect.dart';

class Explosion extends PositionComponent with HasGameReference<FireworkEffect> {
  final Firecracker firecracker;
  final List<Particle> particles;

  Explosion(this.firecracker, this.particles): super(anchor: Anchor.center);

  @override
  void update(double dt) {
    particles.removeWhere((particle) {
      // 更新粒子生命
      particle.life -= 0.015;
      if (particle.life <= 0) {
        return true;
      }

      // 应用重力 (模拟向下的加速度)
      particle.velocityY += 0.15;

      // 应用空气阻力 (速度逐渐减慢)
      particle.velocityX *= 0.98;
      particle.velocityY *= 0.98;

      // 更新位置
      particle.x += particle.velocityX;
      particle.y += particle.velocityY;

      // 更新旋转
      particle.rotation += particle.rotationSpeed;

      bool isAny = particle.x == firecracker.x && particle.y == firecracker.y;

      if (firecracker.isExploding && isAny) {
        firecracker.isFinished = true;
        firecracker.isExploding = false;
      }
      return false;
    });
    if (particles.isEmpty) {
      // print("remove explosion");
      game.world.remove(this);
    }
  }

  @override
  void render(Canvas canvas) {
    Paint paintParticle = Paint();
    Paint paintParticleTail = Paint();
    for (var particle in particles) {
      // 随着生命减少，粒子逐渐变暗、变小
      double alpha = particle.life / particle.maxLife;
      double currentSize = particle.radius * alpha;
      canvas.drawCircle(Offset(particle.x, particle.y), currentSize,
          paintParticle..color = particle.color.withValues(alpha: alpha));
      if (alpha > 0.3) {
        paintParticleTail.color = particle.color.withValues(alpha: alpha * 0.3);
        canvas.drawCircle(Offset(
          particle.x - particle.velocityX * 2,
          particle.y - particle.velocityY * 2,
        ), currentSize * 1.5, paintParticleTail);
      }
    }
  }

}